'use strict';
// userRelation.js
const { formatUser } = require('../utils/formatUser');

module.exports = app => {
  class UserRelationService extends app.Service {

    // 通过followerId查找用户
    async getUsersByFollowerId(followerId) {

      const result = await this.app.model.User.findAndCountAll({
        attributes: ['id', 'userName', 'nickName', 'avatar'],
        limit: 50,
        offset: 0,
        order: [['id', 'desc']],
        include: {
          model: this.app.model.UserRelation,
          where: {
            followerId,
            userId: {
              // sequelize 中的不等于 ne  -> no equal
              // gt
              // lt
              [app.Sequelize.Op.ne]: followerId,
            },
          },
        },
      });
      // result 中 count , rows
      // 格式化用户信息
      const userList = formatUser(result.rows.map(item => item.dataValues));

      return {
        count: result.count,
        userList,
      };
    }

    // 获取关注人列表
    async getFollower(userId) {
      const result = await this.app.model.UserRelation.findAndCountAll({
        limit: 50,
        offset: 0,
        order: [['id', 'desc']],
        include: {
          model: this.app.model.User,
          attributes: ['id', 'userName', 'nickName', 'avatar'],
        },
        where: {
          userId,
          followerId: {
            [app.Sequelize.Op.ne]: userId,
          },
        },
      });
      // rows的结构 = [{ userId, followerId, user: {dataValues} }];
      let userList = result.rows.map(item => item.dataValues);
      // 格式化用户信息
      userList = userList.map(item => {
        const user = item.user.dataValues;
        return formatUser(user);
      });
      return {
        count: result.count,
        userList,
      };

    }

    // 添加关注
    async addFollower(userId, followerId) {
      // 向数据库中添加
      const result = await this.app.model.UserRelation.create({
        userId,
        followerId,
      });

      return result;
    }

    // 取消关注
    async deleteFollower(userId, followerId) {
      // 在数据库中删除
      const result = await this.app.model.UserRelation.destroy({
        where: {
          userId,
          followerId,
        },
      });

      return result > 0;
    }
  }
  return UserRelationService;
};
